import {ScrollView, View, Text} from "@tarojs/components";

import {useCallback, useEffect, useRef, useState} from "react";
import {Cell, Empty, Sticky} from "@antmjs/vantui";
import DateUtils, {DateTab, TimeSlot2} from "@/utils/date_utils";
import Utils from "@/utils/common";
import AssetImage from "@/common/AssetImage";
import {MachineModel} from "@/common/apis/model";
import {appoints} from "@/common/apis/home_datasource";
import RouthPath from "@/common/RouthPath";
import LogUtils from "@/utils/log";
import dayjs from "dayjs";


definePageConfig({
  navigationBarTitleText: '预约时间列表'
});


export interface Order_times_listProps {
  item: DateTab;
  model: MachineModel;
}

export default function Order_times_list() { // Renamed for convention (PascalCase)

  const [timeSlots, setTimeSlots] = useState<TimeSlot2[]>(DateUtils.generateTimeSlots());
  const orderTimes = useRef<Order_times_listProps>()
  const showDay = useRef({
    year: '',
    weekDayName: '',
    date: ''
  });

  const [, setRefresh] = useState({})




  //activeDateId 2024-04-25
  const times = useCallback((activeDateId) => {
    return DateUtils.generateTimeSlotsWithAvailabilityAndTimeCheck(activeDateId, {});
  }, []);

  useEffect(() => {
    const params = Utils.getParamsByRouter(Utils.getI())
    if (params && params.data) {
      orderTimes.current = Utils.getObjectWithUrl<Order_times_listProps>(params.data)
      showDay.current = DateUtils.convertYMDToDateObjectWithDayjs(orderTimes.current!.item.id);
      appoints(orderTimes.current!.model.id).then((res) => {
        if (res) {
          const dailyData = res.find(d => d.time === orderTimes.current!.item.id);
          let bookedSlotsInfo: Record<string, {
            name: string;
            phone: string;
            orderInfo: any;
            endTime?: string;
            mergedSlots: string[];
          }> = {};

          if (dailyData && dailyData.orderDTOList) {
            dailyData.orderDTOList.forEach(order => {
              if (order.bookAllTimes) {
                const bookedTimes = order.bookAllTimes.split(',');
                const sortedTimes = bookedTimes
                  .map(fullDateTime => dayjs(fullDateTime))
                  .filter(time => time.isValid())
                  .sort((a, b) => a.valueOf() - b.valueOf());

                let currentStart: dayjs.Dayjs | null = null;
                let currentEnd: dayjs.Dayjs | null = null;
                let mergedStartTimes: string[] = [];

                sortedTimes.forEach(time => {
                  const timeStr = time.format('HH:mm');
                  if (!currentStart) {
                    currentStart = time;
                    currentEnd = time.add(30, 'minute');
                    mergedStartTimes = [timeStr];
                  } else if (time.isSame(currentEnd)) {
                    currentEnd = time.add(30, 'minute');
                    mergedStartTimes.push(timeStr);
                  } else {
                    const startTimeStr = currentStart.format('HH:mm');
                    let endTimeStr = currentEnd?.format('HH:mm');
                    // 判断 endTimeStr 是否为 00:00，若是则替换为 24:00
                    if (endTimeStr === '00:00') {
                      endTimeStr = '24:00';
                    }
                    if (!bookedSlotsInfo[startTimeStr]) {
                      bookedSlotsInfo[startTimeStr] = {
                        name: order.contacts,
                        phone: order.phone,
                        orderInfo: order,
                        endTime: endTimeStr,
                        mergedSlots: mergedStartTimes
                      };
                    }
                    currentStart = time;
                    currentEnd = time.add(30, 'minute');
                    mergedStartTimes = [timeStr];
                  }
                });

                if (currentStart) {
                  const startTimeStr = currentStart.format('HH:mm');
                  let endTimeStr = currentEnd?.format('HH:mm');
                  // 判断 endTimeStr 是否为 00:00，若是则替换为 24:00
                  if (endTimeStr === '00:00') {
                    endTimeStr = '24:00';
                  }
                  if (!bookedSlotsInfo[startTimeStr]) {
                    bookedSlotsInfo[startTimeStr] = {
                      name: order.contacts,
                      phone: order.phone,
                      orderInfo: order,
                      endTime: endTimeStr,
                      mergedSlots: mergedStartTimes
                    };
                  }
                }
              }
            });

            const updatedSlots: TimeSlot2[] = [];
            const processedStartTimes = new Set<string>();

            timeSlots.forEach(slot => {
              if (processedStartTimes.has(slot.startTime)) {
                return;
              }

              const bookedInfo = bookedSlotsInfo[slot.startTime];
              if (bookedInfo) {
                let timeRange = `${slot.startTime} - ${bookedInfo.endTime || slot.endTime}`;
                updatedSlots.push({
                  ...slot,
                  timeRange,
                  isBooked: true,
                  bookedBy: {
                    name: bookedInfo.name,
                    phone: bookedInfo.phone,
                  },
                  orderInfo: bookedInfo.orderInfo,
                });
                bookedInfo.mergedSlots.forEach(startTime => {
                  processedStartTimes.add(startTime);
                });
              } else {
                updatedSlots.push(slot);
              }
            });

            setTimeSlots(updatedSlots);
          }
        }
      })
      setRefresh({})
    }
  }, [times]);

  return (
    <View style={{height: '100VH'}}>
      <View>
        <Sticky>
          {
            showDay.current ?
              <Cell renderIcon={<Text style={{fontSize: '20px', marginRight: '10px'}}>{showDay.current.year}</Text>}
                renderTitle={<Text
                  style={{fontSize: '30px'}}
                >{showDay.current.date}({showDay.current.weekDayName})</Text>}
                label={orderTimes.current?.model.name}
              /> :
              <Empty description='暂无数据' />
          }
        </Sticky>
      </View>
      <View style={{height: '100VH'}}>
        <ScrollView scrollY style={{
          height: '100%',
        }}
        >
          {
            Utils.isEmpty(timeSlots) ? <Empty description='暂无数据' /> : timeSlots.map((e, index) => {
              return <Cell title={e.timeRange} key={index}
                onClick={() => {
                             LogUtils.info("===")
                             if (e.isBooked) {
                               Utils.navigateTo({
                                 url: Utils.getUrlWithObject(RouthPath.orderDetail, {id: e.orderInfo?.id})
                               })
                             }
                           }}
                renderIcon={<View style={{
                             width: '20px',
                             height: '20px',
                             backgroundColor: e.isBooked ? AssetImage.greenLight : 'white',
                             borderRadius: '50%',
                             marginRight: '10px'
                           }}
                ></View>}
                label={e.isBooked ? `${e.bookedBy.name}(${e.bookedBy.phone})` : ''}
                isLink={e.isBooked}
              >
                {
                  e.isBooked ? <Text style={{fontSize: '12px', color: AssetImage.greenLight}}>已预约</Text> : null
                }
              </Cell>
            })
          }
        </ScrollView>
      </View>
    </View>
  );
}
